package com.example.hl.gobang.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.example.hl.gobang.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yls on 2018/6/13.
 */

public class WuziqiPanel extends View {
    private static final int MAX_COUNT_IN_LINE = 5 ;

    private Bitmap whitePiece;//白棋图片
    private Bitmap blackPiece;//黑棋图片
    private static final String TAG = "WuziqiPanel";
    private static final float MAX_LINES = 10;
    private int mPanelWidth;
    private float mLineHeight;
    private float mChessRatio = 3 * 1.0f/4;//棋子的比例
    private Paint mPaint;
    private boolean isGameOver;
    private ArrayList<Point> mWhiteArray = new ArrayList<>();
    private ArrayList<Point> mBlackArray = new ArrayList<>();
    private boolean isWhite;
    private boolean isWhiteWinner;

    public WuziqiPanel(Context context) {
        super(context);

    }

    public WuziqiPanel(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs,0);
        setBackgroundColor(0x44ff0000);
        initPaint();//初始化画笔
        initBitmap();//初始化棋子图片

    }

    private void initBitmap() {
        blackPiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_b1);
        whitePiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_w2);
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(0x88000000);
        mPaint.setAntiAlias(true);//设置抗锯齿
        mPaint.setDither(true);//设置防抖动
        mPaint.setStyle(Paint.Style.STROKE);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int wMode = MeasureSpec.getMode(widthMeasureSpec);

        int height = MeasureSpec.getSize(heightMeasureSpec);
        int hMode = MeasureSpec.getMode(heightMeasureSpec);
        Log.e(TAG,"onMeasure w = " + width +" h = " + height );

        int panelWidth = Math.min(width,height);

        if (wMode==MeasureSpec.UNSPECIFIED){
            panelWidth=height;
        }else if (hMode==MeasureSpec.UNSPECIFIED){
            panelWidth=width;
        }
        setMeasuredDimension(panelWidth,panelWidth);//设置界面大小
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.e(TAG,"onSizeChanged w = " + w +" h = " + h );
        mPanelWidth = w;//棋盘宽度
        mLineHeight = mPanelWidth * 1.0f / MAX_LINES; //棋盘高度
        int cheessSize = (int) (mLineHeight * mChessRatio);//棋子的大小
        whitePiece = Bitmap.createScaledBitmap(whitePiece,cheessSize,cheessSize,false);///通过图片缩放设置棋子大小
        blackPiece = Bitmap.createScaledBitmap(blackPiece,cheessSize,cheessSize,false);

    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        checkGameOver();
    }

    private void checkGameOver() {
        boolean whiteOnewWin = checkFiveInLine(mWhiteArray);
        boolean blackOneWin = checkFiveInLine(mBlackArray);

        if(whiteOnewWin || blackOneWin){
            isGameOver = true;
            isWhiteWinner = whiteOnewWin;

            String text = isWhiteWinner ? "白棋胜利" : "黑棋胜利";
            showAlert(text);
        }
    }

    private boolean checkFiveInLine(List<Point> points) {
        for(Point p :points){
            int x = p.x;
            int y = p.y;

            boolean win = checkHorizontal(x,y,points);
            if(win) return true;
            win = checkVertical(x,y,points);
            if (win) return true;
            win = checkLeftDiagonal(x,y,points);
            if (win) return true;
            win = checkRightDiagonal(x,y,points);
            if (win) return true;

        }
        return false;
    }

    private boolean checkRightDiagonal(int x, int y, List<Point> points) {
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x - i, y - i))) {
                count++;
            } else {
                break;
            }
        }
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x + i, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == 5) {
            return true;
        }

        return false;

    }

    private boolean checkLeftDiagonal(int x, int y, List<Point> points) {
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x - i, y + i))) {
                count++;
            } else {
                break;
            }
        }
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x + i, y - i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == 5) {
            return true;
        }

        return false;
    }

    private boolean checkVertical(int x, int y, List<Point> points) {
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x, y - i))) {
                count++;
            } else {
                break;
            }
        }
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == 5) {
            return true;
        }

        return false;
    }

    private boolean checkHorizontal(int x, int y, List<Point> points) {
        int count = 1;
        for(int i = 1; i< MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x - i,y))){
                count++;
            }else {
                break;
            }
        }
        for (int i = 1; i < MAX_COUNT_IN_LINE;i++){
            if (points.contains(new Point(x + i,y))){
                count++;
            }else {
                break;
            }
        }
        if (count == 5){
            return true;
        }
        return false;
    }

    private void showAlert(String text) {
        View convertView = LayoutInflater.from(getContext()).inflate(R.layout.alert_result,null);
        TextView alert_result = convertView.findViewById(R.id.result);
        alert_result.setText(text);
        new AlertDialog.Builder(getContext(),R.style.dialog)
                .setView(convertView)
                .show();
    }

    private void drawPieces(Canvas canvas) {
        for(int i = 0,n = mBlackArray.size();i<n;i++){
            Point blackPoint = mBlackArray.get(i);
            canvas.drawBitmap(blackPiece,(blackPoint.x + (1 - mChessRatio) / 2) * mLineHeight,
                    (blackPoint.y + (1 - mChessRatio) / 2) * mLineHeight,null);
        }
        for(int i = 0,n = mWhiteArray.size();i < n;i++){
            Point whitePoint = mWhiteArray.get(i);
            canvas.drawBitmap(whitePiece,(whitePoint.x + (1 - mChessRatio) / 2) * mLineHeight,
                    (whitePoint.y + (1 - mChessRatio) / 2) * mLineHeight,null);
        }
    }

    private void drawBoard(Canvas canvas) {
        for(int i=0;i<MAX_LINES;i++){
            int startX = (int) (mLineHeight/2);//x方向起始位置
            int endX = (int) (mPanelWidth - mLineHeight/2);
            int y = (int
                    ) ((0.5 + i) * mLineHeight);
            canvas.drawLine(startX,y,endX,y,mPaint);
            canvas.drawLine(y,startX,y,endX,mPaint);
        }
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(isGameOver) return false;

        int action = event.getAction();
        if(action == MotionEvent.ACTION_UP){
            int x = (int) event.getX();
            int y = (int) event.getY();

            //用户点击的是一个范围而不是一个坐标点
            Point p = getPoint(x,y);

            if (mWhiteArray.contains(p) || mBlackArray.contains(p)){
                return false;
            }
            if(isWhite){
                mWhiteArray.add(p);
            }else {
                mBlackArray.add(p);
            }
            invalidate();
            isWhite = !isWhite;
            return true;
        }


        return true;
    }

    private Point getPoint(int x, int y) {
        return  new Point((int)(x/mLineHeight),(int)(y/mLineHeight));
    }

    public void start() {
        if (mBlackArray.size() != 0 || mWhiteArray.size() != 0) {
            new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("确定开始新的一局?")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mWhiteArray.clear();
                            mBlackArray.clear();
                            isGameOver = false;
                            isWhiteWinner = false;
                            invalidate();

                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
                    .create().show();

        }
    }

    public void back() {
        if (mBlackArray.size() == 0 & mWhiteArray.size() == 0) {
            return;
        }
        if (isWhite) {
            mBlackArray.remove(mBlackArray.size() - 1);
        } else {
            mWhiteArray.remove(mWhiteArray.size() - 1);
        }
        isWhite = !isWhite;
        invalidate();

    }

    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";
    private static final String INSTANCE_IsWhite = "instance_IsWhite";

    @Override
    protected Parcelable onSaveInstanceState() {

        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE, super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER, isGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, mBlackArray);
        bundle.putBoolean(INSTANCE_IsWhite, isWhite);
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {

        //判断是否是自己存的数据
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            isGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            isWhite = bundle.getBoolean(INSTANCE_IsWhite);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }
        super.onRestoreInstanceState(state);

    }
}
